package com.university.report.user.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.university.report.common.utils.JwtUtil;
import com.university.report.model.entity.Permission;
import com.university.report.model.entity.UserAccount;
import com.university.report.user.handler.UserImportListener;
import com.university.report.user.mapper.UserAccountMapper;
import com.university.report.user.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * @ClassName health_report
 * @Author Jinondo
 * @Date 2021/6/19 23:47
 */
@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    UserAccountMapper userAccountMapper;

    @Override
    public String loginDGUT(Map<String, String> userInfo) {
        String stuNumber = userInfo.get("username");
        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_number",stuNumber);
        UserAccount userAccount = baseMapper.selectOne(queryWrapper);
        List<Permission> permissions = baseMapper.findPermissionByUsername(userAccount.getUsername());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        permissions.forEach(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) {
                grantedAuthorities.add(new SimpleGrantedAuthority(permission.getPermTag()));
            }
        });
        userAccount.setAuthorities(grantedAuthorities);

        String roleName=userAccountMapper.findRoleNameByUserId(userAccount.getUserId());
        userAccount.setRoleName(roleName);
        if (userAccount!=null){
            String jwtToken = JwtUtil.generateJsonWebToken(userAccount);
            return jwtToken;
        }
        return null;
    }

    @Override
    public void exportUserAccount(MultipartFile file){
        try {
            EasyExcel.read(file.getInputStream(),UserAccount.class,new UserImportListener(userAccountMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
